package top.abilities.util.utils;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取客户端ip地址
 */
public class IpAddressUtil {
    /**
     * 获取ip地址
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String xForward = request.getHeader("X-Forwarded-For");
        if (checkNotBlankString(xForward)) {
            int index = xForward.indexOf(",");
            if (index != -1) {
                return xForward.substring(0, index);
            } else {
                return xForward;
            }
        }
        if (checkBlankString(xForward)) {
            xForward = request.getHeader("X-Real-IP");
        }
        if (checkBlankString(xForward)) {
            xForward = request.getHeader("Proxy-Client-IP");
        }
        if (checkBlankString(xForward)) {
            xForward = request.getHeader("WL-Proxy-Client-IP");
        }
        if (checkBlankString(xForward)) {
            xForward = request.getHeader("HTTP_CLIENT_IP");
        }
        if (checkBlankString(xForward)) {
            xForward = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (checkBlankString(xForward)) {
            xForward = request.getRemoteAddr();
        }
        return xForward;
    }

    private static boolean checkBlankString(String xForward) {
        return StringUtils.isEmpty(xForward) || !StringUtils.hasText(xForward) || "unKnown".equalsIgnoreCase(xForward);
    }

    private static boolean checkNotBlankString(String xForward) {
        return !StringUtils.isEmpty(xForward) && StringUtils.hasText(xForward) && !"unKnown".equalsIgnoreCase(xForward);
    }
}
